package com.sk.weichat.ui.account;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sk.weichat.R;
import com.sk.weichat.adapter.MessageLogin;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.PasswordHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.util.EventBusHelper;
import com.sk.weichat.util.Md5Util;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.ToastUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;
import okhttp3.Call;

/**
 * 设置密码/修改密码/忘记密码
 * 忘记密码需要intent传递from=0,默认
 * 设置密码需要intent传递from=1
 * 修改密码需要intent传递from=2
 * update by SWY
 */
public class SetPasswordActivity extends BaseActivity {

    public static final int SET_FROM_SMS = 0;//忘记密码跳转
    public static final int SET_FROM_SMS_HAS_PSW = 1;//忘记密码已有密码
    public static final int SET_FROM_NEW = 2;//设置界面设置新密码跳转
    public static final int SET_FROM_UPDATE = 3;//设置界面修改密码跳转

    public static final int RESULT_SET_PASSWORD = 102;
    private EditText etPassword;
    private ImageView ivClear;
    private TextView tvTips;
    private Button btnSet;
    private String telephone;
    private String areaCode;
    private String sk;
    private int mSetFrom;
    private View tbEye;

    public SetPasswordActivity() {
        noLoginRequired();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_password);
        getSupportActionBar().hide();
        mSetFrom = getIntent().getIntExtra("from", 0);
        telephone = getIntent().getStringExtra("telephone");
        areaCode = getIntent().getStringExtra("areaCode");
        sk = getIntent().getStringExtra("sk");

        initActionBar();
        initView();

        EventBusHelper.register(this);
    }

    private void initActionBar() {
        findViewById(R.id.mergerStatus).setBackgroundColor(ContextCompat.getColor(this,R.color.white));
//        ((ImageView)findViewById(R.id.iv_title_left)).setImageResource(R.drawable.icon_back_black);
        findViewById(R.id.iv_title_left).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initView() {

        TextView tvTitle = findViewById(R.id.tv_password_title);
        if (mSetFrom == SET_FROM_UPDATE || mSetFrom == SET_FROM_SMS_HAS_PSW) {//重置密码
            tvTitle.setText(getString(R.string.change_password));
        } else {//设置密码
            tvTitle.setText(getString(R.string.hint_password));
        }

        etPassword = findViewById(R.id.et_set_psw);
        tbEye=findViewById(R.id.tbEye);
        ivClear = findViewById(R.id.iv_clear_psw);
        ivClear.setOnClickListener(new View.OnClickListener() {//清除输入框
            @Override
            public void onClick(View v) {
                etPassword.setText("");
            }
        });
        tvTips = findViewById(R.id.tv_set_psw_tips);
        btnSet = findViewById(R.id.btn_send_forget);
        btnSet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setPassword();
            }
        });
        PasswordHelper.bindPasswordEye(etPassword, findViewById(R.id.tbEye));
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s == null || s.length() == 0) {
                    ivClear.setVisibility(View.GONE);
                    tbEye.setVisibility(View.GONE);
                    tvTips.setText("");
                    btnSet.setBackgroundResource(R.drawable.bg_border_btn_gray);
                    return;
                }
                ivClear.setVisibility(View.VISIBLE);
                tbEye.setVisibility(View.VISIBLE);
                if(s.length() < 6){
                    tvTips.setText("登录密码长度需在6-15位字符之间");
                    btnSet.setBackgroundResource(R.drawable.bg_border_btn_gray);
                    return;
                }else if(!StringUtils.checkPassword(s.toString())){//登录密码不能是纯数字/字母
                    tvTips.setText("登录密码不能是纯数字/字母");
                    btnSet.setBackgroundResource(R.drawable.bg_border_btn_gray);
                    return;
                }else if (s.length() >= 6) {
                    tvTips.setText("");
                    btnSet.setBackgroundResource(R.drawable.bg_border_btn_blue);
                } else {
                    btnSet.setBackgroundResource(R.drawable.bg_border_btn_gray);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }


    //设置密码
    private void setPassword() {
        String psw = etPassword.getText().toString().replace(" ", "");
        if (TextUtils.isEmpty(psw) || psw.length() < 6) {
            tvTips.setTextColor(this.getResources().getColor(R.color.color_red));
            tvTips.setText(getString(R.string.password_empty_error));
            return;
        }
        if (!StringUtils.checkPassword(psw)) {
            tvTips.setTextColor(this.getResources().getColor(R.color.color_red));
            tvTips.setText("登录密码不能是纯数字、字母");
            return;
        }

        String digestPwd = Md5Util.toMD5(psw);
        Map<String, String> params = new HashMap<>();
        String url;
        if (mSetFrom == SET_FROM_SMS || mSetFrom == SET_FROM_SMS_HAS_PSW) {//忘记密码后设置密码
            url = coreManager.getConfig().SET_PASSWORD;
            String phoneStr = telephone.replace(" ", "");
            params.put("telephone", phoneStr);
            params.put("areaCode", areaCode);
            params.put("sk", sk);
            params.put("newPassword", digestPwd);

        } else {
            url = coreManager.getConfig().USER_PASSWORD_RESET;
            params.put("password", digestPwd);
            params.put("access_token", coreManager.getSelfStatus().accessToken);

        }

        DialogHelper.showMessageProgressDialog(this, "正在设置密码...");
        HttpUtils.get().url(url)
                .params(params)
                .build()
                .execute(new BaseCallback<Void>(Void.class) {

                    @Override
                    public void onResponse(ObjectResult<Void> result) {
                        DialogHelper.dismissProgressDialog();
                        if (result == null) {
                            DialogHelper.dismissProgressDialog();
                            ToastUtil.showErrorData(mContext);
                            return;
                        }
                        if (result.getResultCode() == 1) {//设置成功则关闭 手机号 及 当前页面
                            ToastUtil.showToast(mContext, "密码设置成功");
                            if (SMSForgetPswActivity.smsForgetPswActivity != null) {
                                SMSForgetPswActivity.smsForgetPswActivity.finish();
                            }
                            if (coreManager.getSelf() != null) {
                                coreManager.getSelf().setPassword(digestPwd);
                                coreManager.getSelf().setHavePassword(1);
                                UserDao.getInstance().updatePassword(coreManager.getSelf().getUserId(), digestPwd);     // 更新数据库
                                UserDao.getInstance().updateHavePassword(coreManager.getSelf().getUserId(), 1);
                            }
                            finish();

                        } else {
                            String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.login_failed) : result.getResultMsg();
                            ToastUtil.showToast(mContext, message);
                            tvTips.setText(message);
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showNetError(mContext);
                    }
                });

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void helloEventBus(MessageLogin message) {
        finish();
    }

}
